//
//  ViewController.m
//  轮盘抽奖
//
//  Created by Andrew on 2018/7/18.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "ViewController.h"
#import <MJExtension.h>
#import "YMMaxProModel.h"
#import "YMLotteryModel.h"

@interface ViewController () <CAAnimationDelegate>

/** 开始 */
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
/** go */
@property (weak, nonatomic) IBOutlet UIImageView *startImage;
/** 轮盘 */
@property (weak, nonatomic) IBOutlet UIImageView *prizeImage;
/** 数据 */
@property (copy, nonatomic) NSMutableArray *dataArray;
/** 区间长度 */
@property (assign, nonatomic) NSInteger lotteryCount;
/* 选中的中奖 */
@property (nonatomic, strong) YMLotteryModel *selectedModel;
@property (assign, nonatomic) CGFloat angle;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setData];
}

/**
 修改中奖概率
 */
- (void)changeProbabilityWithModel:(YMLotteryModel *)model
{
    //奖品已经没有了，需要将奖品的中奖区间改为0
    if (model.count == 0) {
        //修改其他的中奖区间
        [self changeRandowWithIndex:model.index changeCount:model.maxIndex - model.minIndex];
        
        //中奖区间为0
        model.minIndex = model.maxIndex;
    }
    
    //如果概率可以改变
    if (model.isProbabilityChage) {
        for (YMMaxProModel *maxModel in model.probabilityArray) {
            if (model.count == maxModel.maxCount) {
                NSInteger changeCount = ([model.probability floatValue] - [maxModel.maxProbability floatValue]) * _lotteryCount;
                
                //修改其他的区间
                [self changeRandowWithIndex:model.index changeCount:changeCount];
                
                //缩小中奖
                model.minIndex += changeCount;
                model.probability = maxModel.maxProbability;
                break;
            }
        }
    }
}


/**
 重新设置中奖区间

 @param index index前的数据才需要设置
 @param changeCount 对应的数据的区间减少量
 */
- (void)changeRandowWithIndex:(NSInteger)index changeCount:(NSInteger)changeCount
{
    //数据问题，第二个间隔是不中奖，所以就增加该间隔的中奖区间
    for (int i = 1; i < index; i++) {
        //将model的区间减小，增加第一个奖品的中间区间（第一个奖品就不是不中奖）
        YMLotteryModel *model = _dataArray[i];
        if (i > 1) {
            model.index += changeCount;
        }
        model.maxIndex += changeCount;
    }
}

- (void)showAlertView {
    NSString *title;
    NSString *message;
    NSString *sureTitle;
    
    if ([_selectedModel.name isEqualToString:@"谢谢惠顾"]) {
        title = @"很遗憾";
        message = @"差点就中大奖了，换个位置再抽一次";
        sureTitle = @"再抽一次";
    }
    else {
        title = @"中奖了";
        message = [NSString stringWithFormat:@"恭喜你获得了%@", _selectedModel.name];
        sureTitle = @"去使用";
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消按钮");
        
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了去使用按钮");
        
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:sureAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}


- (IBAction)startBtnClick:(UIButton *)sender {
    NSInteger index = arc4random() % _lotteryCount;
    
    for (YMLotteryModel *model in _dataArray) {
        if (index >= model.minIndex && index < model.maxIndex) {
            _selectedModel = model;
            
            if (![model.name isEqualToString:@"谢谢惠顾"]) {
                if (model.count != -1 && model.count > 1) {
                    model.count -= 1;
                }
                
                //修改中奖概率
                [self changeProbabilityWithModel:model];
                //显示动画
                [self showAnimationWithSelectedModel:model];
                break;
            } else {
                //显示动画
                [self showAnimationWithSelectedModel:model];
                break;
            }
        }
    }
}

#pragma mark - 动画
- (void)showAnimationWithSelectedModel:(YMLotteryModel *)model
{
    _startBtn.enabled = NO;
    
    NSInteger count = _dataArray.count;
    NSInteger current = 8;
    _angle = M_PI / count + model.index * 2 * M_PI / count * current * 2 * M_PI;
    
    CABasicAnimation *layer = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    layer.toValue = @(_angle);
    layer.duration = _angle / (3 * M_PI);
    layer.removedOnCompletion = NO;
    layer.fillMode = kCAFillModeForwards;
    layer.repeatCount = 0;
    layer.delegate = self;
    
    [_prizeImage.layer addAnimation:layer forKey:nil];
    
}


/**
 指针返回初始位置
 */
- (void)backToStartPosition
{
    CABasicAnimation *layer = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    layer.toValue = @(0);
    layer.duration = 2;
    layer.removedOnCompletion = NO;
    layer.fillMode = kCAFillModeForwards;
    layer.beginTime = CACurrentMediaTime() + 2;//延迟1S后执行

    [_prizeImage.layer addAnimation:layer forKey:nil];
    
    _startBtn.enabled = YES;
}

#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //显示中奖弹窗
    [self showAlertView];
    //设置指针返回初始位置
    [self backToStartPosition];
}

#pragma mark - 创建数据
- (void)setData
{
    NSDictionary *dict1 = @{
                            @"name" : @"10元优惠券",
                            @"index" : @0,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.20"],
                            @"count" : @-1,
                            @"isProbabilityChage" : @0,
                            };
    
    NSDictionary *dict2 = @{
                            @"name" : @"谢谢惠顾",
                            @"index" : @1,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.125"],
                            @"count" : @-1,
                            @"isProbabilityChage" : @0,
                            };
    NSDictionary *dict3 = @{
                            @"name" : @"99元XX牌移动电源购买券",
                            @"index" : @2,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.10"],
                            @"count" : @300,
                            @"isProbabilityChage" : @0,
                            };
    
    NSDictionary *dict4 = @{
                            @"name" : @"谢谢惠顾",
                            @"index" : @3,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.125"],
                            @"count" : @-1,
                            @"isProbabilityChage" : @0,
                            };
    NSDictionary *dict5 = @{
                            @"name" : @"499元XX牌电冰箱购买券",
                            @"index" : @4,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.05"],
                            @"count" : @51,
                            @"isProbabilityChage" : @1,
                            @"probabilityArray" : @[
                                    @{
                                        @"maxCount" : @10,
                                        @"maxProbability" : [NSDecimalNumber decimalNumberWithString:@"0.02"]
                                        },
                                    @{
                                        @"maxCount" : @20,
                                        @"maxProbability" : [NSDecimalNumber decimalNumberWithString:@"0.025"]
                                        },
                                    @{
                                        @"maxCount" : @50,
                                        @"maxProbability" : [NSDecimalNumber decimalNumberWithString:@"0.030"]
                                        }
                                    ]
                            };
    NSDictionary *dict6 = @{
                            @"name" : @"谢谢惠顾",
                            @"index" : @5,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.125"],
                            @"count" : @-1,
                            @"isProbabilityChage" : @0,
                            };
    
    NSDictionary *dict7 = @{
                            @"name" : @"20元优惠券",
                            @"index" : @6,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.15"],
                            @"count" : @-1,
                            @"isProbabilityChage" : @0,
                            };
    
    NSDictionary *dict8 = @{
                            @"name" : @"谢谢惠顾",
                            @"index" : @7,
                            @"probability" : [NSDecimalNumber decimalNumberWithString:@"0.125"],
                            @"count" : @-1,
                            @"isProbabilityChage" : @0,
                            };
    
    NSArray *array = @[dict1, dict2, dict3, dict4, dict5, dict6, dict7, dict8];
    self.dataArray = [YMLotteryModel mj_objectArrayWithKeyValuesArray:array];
    
    //设置整个demo的区间长度
    _lotteryCount = 10000;
    NSInteger min = 0;
    //设置中奖区间
    for (int i = 0; i < _dataArray.count; i++) {
        YMLotteryModel *model = _dataArray[i];
        model.minIndex = min;
        model.maxIndex = model.minIndex + [model.probability floatValue] * _lotteryCount;
        min = model.maxIndex;
    }
    
}

#pragma mark - 懒加载
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}

@end
